#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import datetime

from apps.common import BaseModelClass
from apps.news.spider_qq import api_response, parse_response_data
from init_extends.init_extends import db
from model.model import NewsManage, NewUpdateRecords
from utils.model_to_dict import model_to_dict


class NewsServices(BaseModelClass):
    model_name = NewUpdateRecords

    def filter_date_history(self, date):
        """
        获取指定时间的当天的所有新闻更新记录
        :param date:
        :return:
        """
        return self.model_name.query. \
            filter(db.cast(self.model_name.create_time, db.DATE) == db.cast(date, db.DATE)). \
            order_by(self.model_name.news_id.desc(), self.model_name.hot_score.desc()). \
            all()

    def get_news_by_hot_score(self, date, count):
        """
        获取热搜榜前十的新闻
        :return:
        """
        # 查询指定时间当天的新闻
        top_list = self.filter_date_history(date)
        # 选择热搜值最高的 10 篇
        validate_news = {}
        for d in top_list:
            if len(validate_news.keys()) == count:
                break
            if validate_news.get(d.news_id):
                if d.hot_score > validate_news.get(d.news_id):
                    validate_news[d.news_id] = d.hot_score
            else:
                validate_news[d.news_id] = d.hot_score
        validate_news = list(self.model_name.query.filter(self.model_name.id.in_(validate_news.keys())))
        # 整理需要展示的信息
        detail_news_list = []
        for info in NewsManage.query.filter(NewsManage.id.in_([n.id for n in validate_news])).all():
            info_dict = model_to_dict(info)
            info_dict.update(self.news_hot_score_info(info.n_id))
            detail_news_list.append(info_dict)
        detail_news_list = sorted(detail_news_list, key=lambda d: d['score'], reverse=True)
        return detail_news_list

    def get_news_by_enduring_hot_score(self):
        filter_date = datetime.datetime.now()
        hot_news = self.get_news_by_hot_score(filter_date, 50)

        # first_record = None
        for new_info in hot_news:
            print("\n==================", new_info["title"])
            news = NewsManage.query.filter_by(id=new_info["id"]).first()
            before_history, validate_history = None, []
            for history in news.history:
                if before_history is None:
                    before_history = history
                    continue
                if (before_history.create_time - history.create_time).seconds < 60 * 10:
                    continue
                validate_history.append(history)
            print(len(validate_history) * 10 * 60)
        return hot_news

    @staticmethod
    def news_hot_score_info(news_id):
        """
        根据 news_id 查询新闻一小时内的浏览量、排名、热搜值的变化情况
        :param news_id:
        :return:
        """
        news = NewsManage.query.filter_by(n_id=news_id).first()
        sorted_history = sorted(news.history, key=lambda h: h.create_time, reverse=True)

        news_info = {}
        update_time_list = []
        # 搜索的时间间隔
        hour_seconds = 60 * 60
        for h in sorted_history:
            validate_length = len(update_time_list)
            if validate_length >= 2:
                break
            if validate_length > 0 and (update_time_list[0].create_time - h.create_time).seconds < hour_seconds:
                continue
            update_time_list.append(h)

            news_info['is_top'] = bool(h.is_top)
            news_info["count"] = max(h.read_count, news_info.get("count", 0)) if h.read_count else 0
            news_info["change_score"] = h.hot_score - news_info.get("score", 0)
            news_info["change_rank"] = h.rank_index - news_info.get("rank", 0)
            news_info["score"] = max(h.hot_score, news_info.get("score", 0))
            news_info["rank"] = min(h.rank_index, news_info.get("rank", 100))
        return news_info


class StatisticsNewsManage(BaseModelClass):
    model_name = NewsManage

    # 查询前一天前十条热门新闻




def create_and_update_news():
    """
    同步最新的新闻内容与热搜榜单记录
    :return:
    """
    all_news_list = parse_response_data(api_response())
    for data in all_news_list:
        _, news = BaseModelClass(NewsManage).get_or_create(filter_data=data['id'], create_data={
            "n_id": data['id'],
            "title": data['title'][:50],
            "abstract": data['abstract'],
            "article_type_code": data['article_type_code'],
            "article_type": data['article_type'],
            "url": data['url'],
            "source": data['source'],
            "address": data['address']
        }, filter_field='n_id')
        history = BaseModelClass(NewUpdateRecords).create(**{
            "read_count": data['read_count'],
            "rank_index": data['hot_info']['ranking'],
            "is_top": data['hot_info']['is_top'],
            "hot_score": data['hot_info']['score'],
            "server_update_time": datetime.datetime.fromtimestamp(data['timestamp'])
        })
        news.history.append(history)
        db.session.commit()
